package com.dminvoicemanager;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceNew.DecimalDigitsInputFilter;
import com.dminvoicemanager.adapters.DM_CustomerList_Adapter;
import com.dminvoicemanager.printdoc.DM_Print_Main_Invoice;
import com.dminvoicemanager.printdoc.DM_Print_Main_SalesOrder;
import com.dminvoicemanager.reports.DM_Customer_Last_Three_SO_Visit;
import com.dminvoicemanager.reports.DM_Customer_Last_Three_Visit;
import com.dminvoicemanager.tabs.DM_RetOutstanding_Information;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_InvoiceSalesOrder extends Activity {
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Main Invoice
	/*
	 * private String STOCK_ORDER_INVOICESUMERY = "frepInvoiceSumery"; private
	 * String INV_DETAILS = "FinvDet"; private String INV_HEADER = "FinvHed";
	 */

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Sales Order
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	private SQLiteDatabase mydb;

	final private static int DIALOG_CANCEL_INVOICE = 1;
	final private static int DIALOG_UNDO_INVOICE = 2;
	final private static int DIALOG_PRINT_INVOICE = 3;
	final private static int DIALOG_SAVE_INVOICE = 4;
	final private static int DIALOG_SELECT_CUSTOMER = 5;

	AlertDialog InvoiceHeaderAlert = null;
	static final int DATE_DIALOG_ID = 0;
	private static final String TAG = null;
	Dialog invoiceListDialog;
	String TagId, ReaCode, printDeliverDate;
	int ListInvTag,checkSOitems = 0;
	String invoiceDeliDate;
	// variables to save user selected date and time
	public int yearSelected, monthSelected, daySelected, hourSelected,
			minuteSelected;

	// declare the variables to show the date and time whenTime and Date Picker
	// Dialog first appears
	private int mYear, mMonth, mDay, mHour, mMinute;

	EditText etdminvdate, etdminvcustomer, etdminvremarks, etdminvcusdis,
			etdminvdiscount, etsalesorderdeldate;
	Button INVSelectCustomer, INVSelectItems, INVSave, INVPrint, INVCancel,
			INVUndo, etdminvno, btnSelectStOrder, CusListAllViewBtn,popup_invmenubut;
	LinearLayout ListViewShowCustomers, ListViewInvHeaderButton,
			ListViewInvHeaderDetails, ListViewselectinvoices;
	String match = "5";
	String invoiceSerial, InvoiceCustomerCode;
	String PrintTotalDiscountValue, PrintDiscountedInvValueItems,
			PrintTotCustomerInvDiscount, UserDealCode, UserAreaCode,
			UserRouteCode,slectedMenuOption;
	String invcuscode, invcusname, invcusdiscount, currentInvoiceTempRefCode,
			invheadcode, currentSerial, currentPreInvoiceCode, ReasonDesc = "";
	EditText marketretval, invoicetotval, invoicedisval, etdmsalesordermanuno,
			myFilterCustomer, etdminvCusdiscount;
	double InvDiscountValueItems = 0.0, InvValueItems = 0.0,
			InvValueItemsReturned = 0.0, InvDiscountValueCustomer = 0.0,
			TotCustomerInvDiscount = 0.0, TotalDiscountValue = 0.0,
			DiscountedInvValueItems = 0.0;
	double StrInvDisRatioAmountManu = 0.00;
	double StrInvDisRatioAmount = 0.00;
	double ratio = 0.00;
	double ratioManu = 0.00;
	double StrManualInvAmount = 0.00;
	double StrManualInvAmountManu = 0.00;
	double StrManualDiscount = 0.00;
	double StrMainInvValTot = 0.00;
	double StrMainInvDisValTot = 0.00;
	double StrMainLineDisValTot = 0.00;
	double RefNoItemQty = 0.0;
	double CurrentStockVal = 0.0;
	String MainUserLocCode = "MS";
	String activeInvoiceCode = "1", currentUserTemp, currentUserPrefix,
			refNoSummaryInvoice, UserLocCode, deviceUser = "ANDROID";
	RelativeLayout customerSearchBox;
	String RepInvCode, TransTypePrefix, AgentPrefixType, LatestInvNumber,
			LatestInvState, ActiveInvoice, strLatestInvoiceSerial;
	int ButtonTag, SAVETAG = 0, CANCELTAG = 0, customerReloadTag = 202;;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

	private DM_CustomerList_Adapter dbHelperCustomer;
	private SimpleCursorAdapter dataAdapterCusomer;

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// ============Cancel Invoice===================
	public void btnCancelInvoice(View view) {
		checkSalesOrderUploaded();
		
	}

	private void checkSalesOrderUploaded() {
		// TODO Auto-generated method stub
		String currentRef = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkInvoiceUpload = null;
		try {
			chkInvoiceUpload = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
					+ currentRef + "' AND stordhedSync ='1'", null, null, null, null);
		} catch (Exception e) {
		}
		if (chkInvoiceUpload != null) {
			if (chkInvoiceUpload.getCount() > 0) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_InvoiceSalesOrder.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ERROR CANCEL SALES ORDER");
				// Setting Dialog Message
				alertDialog.setMessage("Selected Sales Order Already Uploaded.Not Authorized To Cancel..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
			else{
				checkInvoiceUsed();
			}
		}else{
			checkInvoiceUsed();
		}
	}

	private void checkInvoiceSaved() {
		// TODO Auto-generated method stub
		String CurrentInvoiceRefNoChk = etdminvno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentStLoadRefCur = null;
		try {
			CurrentStLoadRefCur = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"repusername='" + currentUserTemp + "' AND invoiceRef='"
							+ CurrentInvoiceRefNoChk + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (CurrentStLoadRefCur != null) {
			if (CurrentStLoadRefCur.getCount() > 0) {
				CANCELTAG = 0;
				SAVETAG = 99;
			} else {
				CANCELTAG = 45;
			}
		}
		CurrentStLoadRefCur.close();
		mydb.close();
	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		// synchdata();

		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			latestInvoiceRecord();
			SaveMainInvoice();

		}
		// Update fItemLoc Items Quantity
		// UpdateStockQuantityOnCancel();=>need to implement
		// Update Sync State Not To upload Canceled Invoices
		// UpdateSyncState();=>need to implement
		UpdateSyncStateOnCancel();
		updateInvoiceCancelState();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

	}
	// Update Sync State Not To upload Canceled Invoices
		private void UpdateSyncStateOnCancel() {
			// TODO Auto-generated method stub
			Log.v(TAG, "*****UpdateSyncState*****");
			String RefNoCode = etdminvno.getText().toString();
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor curUpdateSyncStateInvHed = null;
			Cursor curUpdateSyncStateInvDet = null;

			try {
				curUpdateSyncStateInvHed = mydb.query(STOCK_ORDER_HEAD, null, "RefNo='"
						+ RefNoCode + "'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				curUpdateSyncStateInvDet = mydb.query(STOCK_ORDER_DETAIL, null, "RefNo='"
						+ RefNoCode + "'", null, null, null, null);
			} catch (Exception e) {
			}

			if (curUpdateSyncStateInvHed != null) {
				if (curUpdateSyncStateInvHed.getCount() > 0) {
					while (curUpdateSyncStateInvHed.moveToNext()) {
						ContentValues conInvHedValUpdate = new ContentValues();
						
						conInvHedValUpdate.put("stordhedSync", "3");
						mydb.update(STOCK_ORDER_HEAD, conInvHedValUpdate, "RefNo ='"
								+ RefNoCode + "'", null);
					}
				}
			}

			if (curUpdateSyncStateInvDet != null) {
				if (curUpdateSyncStateInvDet.getCount() > 0) {
					while (curUpdateSyncStateInvDet.moveToNext()) {
						ContentValues conInvDetValUpdate = new ContentValues();
						conInvDetValUpdate.put("storddetSync", "3");
						mydb.update(STOCK_ORDER_DETAIL, conInvDetValUpdate, "RefNo ='"
								+ RefNoCode + "'", null);
					}
				}
			}
			
			curUpdateSyncStateInvHed.close();
			curUpdateSyncStateInvDet.close();
			mydb.close();
		}
	// ==============Undo Invoice====================
	public void btnUndoInvoice(View view) {
		if (etdminvno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if (etdminvno.length() != 0) {
				latestInvoiceRecord();
				updateInvoiceUndoState();
				clearInvoiceUndoFields();
				InvoiceHeaderAlert.dismiss();
			}

		} else if (ListInvTag == 99) {
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		}
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		// synchdata();
		invoiceTransType();
		agentPrefix();
		if (ListInvTag != 99) {
			if (etdminvno.length() != 0) {
				latestInvoiceRecord();
				updateInvoiceUndoState();
				clearInvoiceUndoFields();
				InvoiceHeaderAlert.dismiss();
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceMenu.class);
				myIntent.putExtra("TAGID", "SALES");
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		}

		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

		/*
		 * if (etdminvno.length() != 0) {
		 * 
		 * }
		 */
		InvoiceHeaderAlert.dismiss();
	}

	private void clearInvoiceUndoFields() {
		// TODO Auto-generated method stub
		etdminvno.setText("");
		etdminvdate.setText(getCurrentTimeString().toString());
		etdminvcustomer.setText("");
		etdminvremarks.setText("");
		etdminvcusdis.setText("");
		etdminvdiscount.setText("");
		marketretval.setText("");
		invoicedisval.setText("");
		invoicetotval.setText("");
		etdminvCusdiscount.setText("");
	}

	// ------------------List Invoice Dialog Dissmis-----------------
	public void btnClickDialogDissmiss(View view) {
		invoiceListDialog.dismiss();
	}

	// ------------------Print Invoice-----------------
	public void btnPrintInvoice(View view) {
		if (etdminvno.length() != 0) {
			checkInvoiceSaved();
			if (SAVETAG == 99) {
				String currentPrintRefNo = etdminvno.getText().toString();
				String invoiceDeliveryDate = btnSelectStOrder.getText()
						.toString();
				Intent myIntent = new Intent(view.getContext(),
						DM_Print_Main_SalesOrder.class);
				myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
				myIntent.putExtra("TAGIDREFDATE", invoiceDeliveryDate);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			} else {
				SAVETAG = 0;
				showDialog(DIALOG_PRINT_INVOICE);
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT INVOICE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Invoice");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	private void checkInvoiceItems() {
		// TODO Auto-generated method stub
		//checkSOitems
		String InvoiceRef = etdminvno.getText().toString().trim();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CheckSalesItems = null;
		try {
			CheckSalesItems = mydb.query(TEMPSTOCK_ORDER_DETAIL, null,
					"RefNo='" + InvoiceRef + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (CheckSalesItems != null) {
			if (CheckSalesItems.getCount() > 0) {
				checkSOitems = 202;
			}
		}
	}

	private void checkInvoiceUsed() {
		// TODO Auto-generated method stub
		String CurrentInvoiceRefNoChk = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CheckSalesOrdUse = null;
		try {
			CheckSalesOrdUse = mydb.query(STOCK_ORDER_HEAD, null,
					"RepCode='" + currentUserTemp + "' AND RefNo='"
							+ CurrentInvoiceRefNoChk + "' AND stOrderComplete ='1'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (CheckSalesOrdUse != null) {
			if (CheckSalesOrdUse.getCount() > 0) {
				Log.v(TAG, "99999999999  Used");
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_InvoiceSalesOrder.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("SALES ORDER CANCEL ERROR");
				// Setting Dialog Message
				alertDialog.setMessage("Not Authorized to Cancel.Selected Sales Order Used In Invoice.");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
			else{
				checkInvoiceSaved();
				if (CANCELTAG == 45) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_InvoiceSalesOrder.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("CANCEL INVALID SALES ORDER");
					// Setting Dialog Message
					alertDialog.setMessage("Current Sales Order Not Saved..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							CANCELTAG = 0;
							alertDialog.dismiss();
						}
					});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					if (etdminvno.length() != 0) {
						try {
							ButtonTag = 3;
							showDialog(DIALOG_CANCEL_INVOICE);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					else {
						ShowInvoiceList();
					}
				}
			}
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		SaveMainInvoice();
		String currentPrintRefNo = etdminvno.getText().toString();
		String invoiceDeliveryDate = btnSelectStOrder.getText().toString();
		Intent myIntent = new Intent(view.getContext(),
				DM_Print_Main_SalesOrder.class);
		myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
		myIntent.putExtra("TAGIDREFDATE", invoiceDeliveryDate);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// ====Save Invoice==========
	// Save invoice details and invoice header details to activate invoice
	public void btnSaveInvoice(View view) {
		checkInvoiceItems();
		if(checkSOitems == 202){
			AlertDialog.Builder builder = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this);
			builder.setTitle("SAVE NEW INVOICE");
			builder.setMessage("Are Sure You Want To Save This Sales Order...");
			builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					ButtonTag = 2;
					SaveMainInvoice();
				}
			});
			builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					Toast.makeText(getApplicationContext(),
							"Cancel Save Sales Order..", Toast.LENGTH_LONG).show();
				}
			});
			builder.show(); // To show the AlertDialog
		}
		else{
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID INVOICE");
			// Setting Dialog Message
			alertDialog.setMessage("No Items For Current Invoice. Please Add Items To Invoice");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		
	}

	}

	public void btnSaveInvoiceAccept(View view) {
		if (etdminvno.length() != 0) {
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			InvoiceHeaderAlert.dismiss();
			finish();

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceSalesOrder.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SALES ORDER ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Sales Order Not Found");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// ------------------Select Customer Invoice-----------------
	public void btnSelectCustomerAccept(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	// Back to Invoice header without selecting Customer
	public void btnCusListBack(View view) {
		customerReloadTag = 202;
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	private void SaveMainInvoice() {
		Log.v(TAG, "*****SaveMainInvoice*****");
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addnewInvoiceHeader = new ContentValues();
			addnewInvoiceHeader.put("RefNo", etdminvno.getText().toString());
			addnewInvoiceHeader.put("RefNo1", etdminvno.getText().toString());
			addnewInvoiceHeader.put("InvType", "1");
			addnewInvoiceHeader
					.put("TxnDate", etdminvdate.getText().toString());
			addnewInvoiceHeader.put("ManuRef", "");
			addnewInvoiceHeader.put("DealCode", UserDealCode);
			addnewInvoiceHeader.put("RepCode", currentUserTemp);
			addnewInvoiceHeader.put("AreaCode", UserAreaCode);
			addnewInvoiceHeader.put("RouteCode", UserRouteCode);
			addnewInvoiceHeader.put("DebCode", invcuscode);
			addnewInvoiceHeader.put("LocCode", UserLocCode);
			addnewInvoiceHeader.put("Remarks", etdminvremarks.getText()
					.toString());
			addnewInvoiceHeader.put("CostCode", "000");
			addnewInvoiceHeader.put("CurCode", "LKR");
			addnewInvoiceHeader.put("CurRate", "1.00");
			addnewInvoiceHeader.put("TxnType", "21");
			addnewInvoiceHeader.put("InvAmt", invoicetotval.getText()
					.toString().replaceAll("[,]", ""));
			if (etdminvcusdis.length() != 0) {
				addnewInvoiceHeader.put("OutDis", etdminvcusdis.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("OutDis", "0.00");
			}

			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("InvDis", etdminvdiscount.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("InvDis", "0.00");
			}
			if (marketretval.length() != 0) {
				addnewInvoiceHeader.put("TotMkrAmt", marketretval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("TotMkrAmt", "0.00");
			}

			addnewInvoiceHeader.put("UnOvAmt", "0.00");
			if (invoicedisval.length() != 0) {
				addnewInvoiceHeader.put("TotalDis", invoicedisval.getText()
						.toString());
			} else {
				addnewInvoiceHeader.put("TotalDis", "0.00");
			}
			addnewInvoiceHeader.put("TotalAmt", invoicetotval.getText()
					.toString().replaceAll("[,]", ""));
			addnewInvoiceHeader.put("AddUser", currentUserTemp);
			addnewInvoiceHeader.put("AddDateInvHead", getCurrentTimeString()
					.toString());
			addnewInvoiceHeader.put("AddMach", deviceUser);
			addnewInvoiceHeader.put("prtcopy", "0");
			addnewInvoiceHeader.put("RecordId", "1");
			addnewInvoiceHeader.put("timestamp_column", getCurrentTimeString()
					.toString());

			invheadcode = etdminvno.getText().toString();
			String[] accountdetail = invheadcode.split("/");
			String invSerialCode = accountdetail[0]; // invSerialCode
			String invSerialNo = accountdetail[1]; // invSerialNo
			Integer i = new Integer(invSerialNo);
			int Serialnum = i.intValue();
			currentSerial = Integer.toString(Serialnum);

			addnewInvoiceHeader.put("refInvoiceHeaderNo", currentSerial);
			addnewInvoiceHeader.put("refInvoiceHeaderCode", etdminvno.getText()
					.toString());

			mydb.insert(TEMPSTOCK_ORDER_HEAD, null, addnewInvoiceHeader);
			invoiceTransType();
			agentPrefix();
			latestInvoiceRecord();
			MapStockOrders();
			MapStockOrdersDetails();
			UpdateStockQuantity();
			updateInvoiceCurrentState();
			if (ButtonTag == 2) {
				try {
					showDialog(DIALOG_SAVE_INVOICE);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			addNewInvoice();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();

	}

	private void UpdateStockQuantity() {
		// TODO Auto-generated method stub
		// Log.v(TAG, "*****UpdateStockQuantity*****");
		String RefNoCode = etdminvno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUpdateBalQty = null;
		Cursor curUpdateItemLocBalQty = null;
		try {
			curUpdateBalQty = mydb.query(STOCK_ORDER_DETAIL, null, "RefNo='"
					+ RefNoCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUpdateBalQty != null) {
			if (curUpdateBalQty.getCount() > 0) {
				while (curUpdateBalQty.moveToNext()) {
					String StrRefNoItemTxn = curUpdateBalQty.getString(22);
					String RefNoItemCode = curUpdateBalQty.getString(12);
					String StrRefNoItemQty = curUpdateBalQty.getString(14);
					
					/*
					 * Log.v(TAG, "QOH :" + RefNoCode + ":" + RefNoItemCode +
					 * "=" + UserLocCode);
					 */
					RefNoItemQty = Double.parseDouble(StrRefNoItemQty);
					// Update Items Location Quantities UserLocCode
					try {
						curUpdateItemLocBalQty = mydb
								.query(ITEM_LOC_DETAILS, null, "Itemcode='"
										+ RefNoItemCode + "' AND LocCode='"
										+ MainUserLocCode + "'", null, null, null,
										null);
					} catch (Exception e) {
					}

					if (curUpdateItemLocBalQty != null) {
						if (curUpdateItemLocBalQty.getCount() > 0) {
							while (curUpdateItemLocBalQty.moveToNext()) {
								ContentValues valueUpdateCurStock = new ContentValues();
								String StrCurrentStock = curUpdateItemLocBalQty
										.getString(3);
								String StrCurRecordId = curUpdateItemLocBalQty
										.getString(4);
								if (StrRefNoItemTxn.equals("22")
										|| StrRefNoItemTxn.equals("27")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "-" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											- RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								} else if (StrRefNoItemTxn.equals("25")
										|| StrRefNoItemTxn.equals("31")) {
									CurrentStockVal = Double
											.parseDouble(StrCurrentStock);
									/*
									 * Log.v(TAG, "QOH UPDATE:" +
									 * CurrentStockVal + "+" + RefNoItemQty);
									 */
									CurrentStockVal = CurrentStockVal
											+ RefNoItemQty;
									String PrintCurrentStockVal = Double
											.toString(CurrentStockVal);
									valueUpdateCurStock.put("QOH",
											PrintCurrentStockVal);
									valueUpdateCurStock.put("syncRec", "0");
									mydb.update(ITEM_LOC_DETAILS,
											valueUpdateCurStock, "RecordId ='"
													+ StrCurRecordId + "'",
											null);
								}

							}
						} else {
							Log.v(TAG, "QOH UPDATE ERROR");
						}
					}
					// =======================================================
				}
			}
		}
		curUpdateItemLocBalQty.close();
		curUpdateBalQty.close();
		mydb.close();

	}


	// Save data in to original DB
	private void MapStockOrders() { // invheadcode
		// TODO Auto-generated method stub
		Log.v(TAG, "DELIEVER DATE :"+ btnSelectStOrder.getText().toString());
		
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curTempStOrderHed = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			curTempStOrderHed = mydb.query(TEMPSTOCK_ORDER_HEAD, null,
					"RefNo='" + invheadcode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		try {
			if (curTempStOrderHed != null) {
				if (curTempStOrderHed.getCount() > 0) {
					while (curTempStOrderHed.moveToNext()) {
						String RefNo = curTempStOrderHed.getString(1);
						String TxnDate = curTempStOrderHed.getString(4);
						String ManuRef = curTempStOrderHed.getString(5);
						String DealCode = curTempStOrderHed.getString(6);
						String RepCode = curTempStOrderHed.getString(7);
						String AreaCode = curTempStOrderHed.getString(8);
						String RouteCode = curTempStOrderHed.getString(9);
						String DebCode = curTempStOrderHed.getString(10);
						String LocCode = curTempStOrderHed.getString(11);
						String Remarks = curTempStOrderHed.getString(12);
						String CostCode = curTempStOrderHed.getString(13);
						String CurCode = curTempStOrderHed.getString(14);
						String CurRate = curTempStOrderHed.getString(15);
						String TxnType = curTempStOrderHed.getString(16);
						String InvAmt = curTempStOrderHed.getString(17);
						String OutDis = curTempStOrderHed.getString(18);
						String InvDis = curTempStOrderHed.getString(19);
						String TotMkrAmt = curTempStOrderHed.getString(20);
						String UnOvAmt = curTempStOrderHed.getString(21);
						String TotalDis = curTempStOrderHed.getString(22);
						String TotalAmt = curTempStOrderHed.getString(23);
						String AddUser = curTempStOrderHed.getString(24);
						String AddDateInvHead = curTempStOrderHed.getString(25);
						String AddMach = curTempStOrderHed.getString(26);
						String prtcopy = curTempStOrderHed.getString(27);
						String RecordId = curTempStOrderHed.getString(28);
						try {
							ContentValues savefStOrdHed = new ContentValues();
							savefStOrdHed.put("AddMach", AddMach);
							savefStOrdHed.put("AddUser", AddUser);
							savefStOrdHed.put("AreaCode", AreaCode);
							savefStOrdHed.put("CostCode", CostCode);
							savefStOrdHed.put("CurCode", CurCode);
							savefStOrdHed.put("CurRate", CurRate);
							savefStOrdHed.put("DealCode", DealCode);
							savefStOrdHed.put("DebCode", DebCode);
							savefStOrdHed.put("InvAmt", InvAmt);
							savefStOrdHed.put("InvDis", InvDis);
							savefStOrdHed.put("InvFlg", "0");
							savefStOrdHed.put("LocCode", LocCode);
							savefStOrdHed.put("ManuRef", ManuRef);
							savefStOrdHed.put("OutDis", OutDis);
							savefStOrdHed.put("RecordId", RecordId);
							savefStOrdHed.put("RefNo", RefNo);
							savefStOrdHed.put("Remarks", Remarks);
							savefStOrdHed.put("RepCode", RepCode);
							savefStOrdHed.put("RouteCode", RouteCode);
							savefStOrdHed.put("TotMkrAmt", TotMkrAmt);
							savefStOrdHed.put("TotalAmt", TotalAmt);
							savefStOrdHed.put("TotalDis", TotalDis);
							savefStOrdHed.put("TranBatch", "");
							savefStOrdHed.put("TxnType", "21");
							savefStOrdHed.put("UnOvAmt", UnOvAmt);
							savefStOrdHed.put("prtcopy", prtcopy);
							savefStOrdHed.put("TxnDate", TxnDate);
							savefStOrdHed.put("stOrderComplete", "0");
							savefStOrdHed.put("stordhedSync", "0");
							savefStOrdHed.put("outDisVal", etdminvCusdiscount
									.getText().toString());
							savefStOrdHed.put("ohAddDate",
									getAddDateTimeString().toString());
							savefStOrdHed.put("delvDate", btnSelectStOrder
									.getText().toString());
							mydb.insert(STOCK_ORDER_HEAD, null, savefStOrdHed);
						} catch (Exception e) {
						}

					}
				}

			}
		} catch (Exception e) {
		}
		curTempStOrderHed.close();
		mydb.close();
	}

	private void MapStockOrdersDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curTempStOrderDet = null;
		try {
			curTempStOrderDet = mydb.query(TEMPSTOCK_ORDER_DETAIL, null,
					"RefNo='" + invheadcode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		try {

			if (curTempStOrderDet != null) {
				if (curTempStOrderDet.getCount() > 0) {
					while (curTempStOrderDet.moveToNext()) {
						String RefNo = curTempStOrderDet.getString(1);
						String TxnDate = curTempStOrderDet.getString(2);
						String TxnType = curTempStOrderDet.getString(3);
						String SeqNo = curTempStOrderDet.getString(4);
						String Itemcode = curTempStOrderDet.getString(5);
						String Txnseqno = curTempStOrderDet.getString(6);
						String SellPrice = curTempStOrderDet.getString(7);
						String BSellPrice = curTempStOrderDet.getString(8);
						String TSellPrice = curTempStOrderDet.getString(9);
						String BTSellPrice = curTempStOrderDet.getString(10);
						String CostPrice = curTempStOrderDet.getString(11);
						String CaseQty = curTempStOrderDet.getString(12);
						String Type = curTempStOrderDet.getString(13);
						String PiceQty = curTempStOrderDet.getString(14);
						String Qty = curTempStOrderDet.getString(15);
						String BalQty = curTempStOrderDet.getString(16);
						String DisPer = curTempStOrderDet.getString(17);
						String DisAmt = curTempStOrderDet.getString(18);
						String BDisAmt = curTempStOrderDet.getString(19);
						String TaxAmt = curTempStOrderDet.getString(20);
						String BTaxAmt = curTempStOrderDet.getString(21);
						String Amt = curTempStOrderDet.getString(22);
						String BAmt = curTempStOrderDet.getString(23);
						ReaCode = curTempStOrderDet.getString(24);
						String RecordId = curTempStOrderDet.getString(26);
						String casePicesUnits = curTempStOrderDet.getString(30);
						ReasonDesc = curTempStOrderDet.getString(32);
						String DisPercentage = curTempStOrderDet.getString(33);
						String DisPercentageVal = curTempStOrderDet
								.getString(34);
						String odetAddDate = curTempStOrderDet.getString(35);
						String itemUnitPrice = curTempStOrderDet.getString(36);
						try {
							ContentValues savefStOrdDet = new ContentValues();
							savefStOrdDet.put("RefNo", RefNo);
							savefStOrdDet.put("TxnDate", TxnDate);
							savefStOrdDet.put("TxnType", TxnType);
							savefStOrdDet.put("SeqNo", SeqNo);
							savefStOrdDet.put("Itemcode", Itemcode);
							savefStOrdDet.put("Txnseqno", Txnseqno);
							savefStOrdDet.put("SellPrice", SellPrice);
							savefStOrdDet.put("BSellPrice", BSellPrice);
							savefStOrdDet.put("TSellPrice", TSellPrice);
							savefStOrdDet.put("BTSellPrice", BTSellPrice);
							savefStOrdDet.put("CostPrice", CostPrice);
							savefStOrdDet.put("CaseQty", CaseQty);
							savefStOrdDet.put("Type", Type);
							savefStOrdDet.put("PiceQty", PiceQty);
							savefStOrdDet.put("Qty", Qty);
							savefStOrdDet.put("BalQty", BalQty);
							savefStOrdDet.put("DisPer", DisPer);
							savefStOrdDet.put("DisAmt", DisAmt);
							savefStOrdDet.put("BDisAmt", BDisAmt);
							savefStOrdDet.put("TaxAmt", TaxAmt);
							savefStOrdDet.put("BTaxAmt", BTaxAmt);
							savefStOrdDet.put("Amt", Amt);
							savefStOrdDet.put("BAmt", BAmt);
							savefStOrdDet.put("ReaCode", ReaCode);
							savefStOrdDet.put("RecordId", RecordId);
							savefStOrdDet.put("storddetSync", "0");
							savefStOrdDet.put("itemdisper", DisPercentage);
							savefStOrdDet
									.put("itemdisperval", DisPercentageVal);
							savefStOrdDet.put("reasonDesc", ReasonDesc);
							savefStOrdDet.put("odAddDate", odetAddDate);
							savefStOrdDet.put("itemUnitPrice", itemUnitPrice);
							savefStOrdDet.put("caseUnitsQty", casePicesUnits);
							mydb.insert(STOCK_ORDER_DETAIL, null, savefStOrdDet);
						} catch (Exception e) {
						}
					}
				}
			}

		} catch (Exception e) {
		}
		curTempStOrderDet.close();
		mydb.close();
	}

	// Update current invoice state
	private void updateInvoiceCurrentState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"tempRepInvSerial='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();
						valueupdateInvHead.put("activeInvoiceRemarks",
								etdminvremarks.getText().toString());
						valueupdateInvHead.put("activeInvCusDiscountValue",
								etdminvdiscount.getText().toString());
						valueupdateInvHead.put("invoiceComplete", "2");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvCusDiscount",
								etdminvcusdis.getText().toString());
						valueupdateInvHead.put("activeInvCusDiscountValue",
								etdminvCusdiscount.getText().toString());

						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						valueupdateInvHead.put("invoiceRef", etdminvno
								.getText().toString());

						mydb.update(STOCK_ORDER_INVOICESUMERY,
								valueupdateInvHead, "tempRepInvSerial="
										+ currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	// Update current invoice Cancel state
	private void updateInvoiceCancelState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecup = mydb.query(STOCK_ORDER_INVOICESUMERY,
					columsup, "tempRepInvSerial='" + currentSerial + "'", null,
					null, null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdateInvHead = new ContentValues();

						valueupdateInvHead.put("invoiceComplete", "5");// Invoice
																		// Save
																		// Complete
						valueupdateInvHead.put("activeInvoice", "0");
						valueupdateInvHead.put("invlateststate", "0");
						mydb.update(STOCK_ORDER_INVOICESUMERY,
								valueupdateInvHead, "tempRepInvSerial="
										+ currentSerial, null);
					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecup.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
	}

	// Update current invoice Undo state
	private void updateInvoiceUndoState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecupdate = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrecupdate = mydb.query(STOCK_ORDER_INVOICESUMERY,
					columsup, "tempRepInvSerial='" + currentSerial + "'", null,
					null, null, null);
		} catch (Exception e) {
		}

		try {
			if (selectLastinvrecupdate != null) {
				if (selectLastinvrecupdate.getCount() > 0) {
					while (selectLastinvrecupdate.moveToNext()) {
						ContentValues valueupdateInvHeadUpdate = new ContentValues();
						valueupdateInvHeadUpdate.put("invoiceComplete", "0");// Invoice
																				// Save
																				// Complete
						valueupdateInvHeadUpdate.put("activeInvoice", "1");
						valueupdateInvHeadUpdate.put("activeInvoiceValue", "0");
						valueupdateInvHeadUpdate.put("activeInvItemDiscount",
								"0");
						valueupdateInvHeadUpdate.put("activeInvCusDiscount",
								"0");
						valueupdateInvHeadUpdate.put(
								"activeInvCusDiscountValue", "0");
						valueupdateInvHeadUpdate
								.put("InvoiceCustomerCode", "0");
						valueupdateInvHeadUpdate.put("InvoiceCustomerName", "");
						valueupdateInvHeadUpdate.put("InvoiceSynchState", "0");
						valueupdateInvHeadUpdate.put("recordDate",
								getCurrentTimeString());  
						valueupdateInvHeadUpdate.put("recordSynchDate", "0");
						if (ListInvTag != 99) {
							valueupdateInvHeadUpdate.put("invlateststate", "9");
						} else {
							valueupdateInvHeadUpdate.put("invlateststate", "0");
						}
						valueupdateInvHeadUpdate.put(
								"activeInvoiceReturnValue", "0");
						valueupdateInvHeadUpdate.put("activeInvoiceRemarks",
								etdminvremarks.getText().toString());
						valueupdateInvHeadUpdate.put("invoiceNoOfItems", "0");

						mydb.update(STOCK_ORDER_INVOICESUMERY,
								valueupdateInvHeadUpdate, "tempRepInvSerial="
										+ currentSerial, null);

					}
				} else {

					Toast.makeText(getApplicationContext(),
							"Error in update 1", Toast.LENGTH_SHORT).show();
				}
				selectLastinvrecupdate.close();
			}

			else {
				Toast.makeText(getApplicationContext(), "Error in update 2",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
		}
		mydb.close();
		// Delete records from invoice items details
		deleteUndoInvoiceItems();
	}

	private void deleteUndoInvoiceItems() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor undoinvitemslist = null;
		String columsup[] = { "refInvoiceDetNo" };
		try {
			undoinvitemslist = mydb.query(TEMPSTOCK_ORDER_DETAIL, columsup,
					"refInvoiceDetNo='" + currentSerial + "'", null, null,
					null, null);
		} catch (Exception e) {
		}

		if (undoinvitemslist != null) {
			if (undoinvitemslist.getCount() > 0) {
				while (undoinvitemslist.moveToNext()) {
					mydb.delete(TEMPSTOCK_ORDER_DETAIL, "refInvoiceDetNo ='"
							+ currentSerial + "'", null);
				}
			}
		}
		undoinvitemslist.close();
		mydb.close();
	}

	// Once complete current invoice will generate new invoice
	private void addNewInvoice() {
		// TODO Auto-generated method stub
		Log.v(TAG, "****addNewInvoice****");
		int preInvoiceNo = Integer.parseInt(currentSerial);
		int newInvoiceNo = preInvoiceNo + 1;
		LatestInvNumber = String.valueOf(newInvoiceNo);
		ActiveInvoice = "1";
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues saveTempuserinvoice = new ContentValues();
			saveTempuserinvoice.put("repusername", currentUserTemp);
			saveTempuserinvoice.put("repprefix", currentUserPrefix);
			saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
			saveTempuserinvoice.put("tempRepInvSerial", LatestInvNumber);
			saveTempuserinvoice.put("invoiceComplete", "0");
			saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
			saveTempuserinvoice.put("activeInvoiceValue", "0");
			saveTempuserinvoice.put("activeInvItemDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
			saveTempuserinvoice.put("InvoiceCustomerCode", "0");
			saveTempuserinvoice.put("InvoiceCustomerName", "");
			saveTempuserinvoice.put("InvoiceSynchState", "0");
			saveTempuserinvoice.put("recordDate", getCurrentTimeString());
			saveTempuserinvoice.put("recordSynchDate", "0");
			saveTempuserinvoice.put("invlateststate", "9");
			saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
			saveTempuserinvoice.put("activeInvoiceRemarks", "");
			saveTempuserinvoice.put("invoiceNoOfItems", "0");
			saveTempuserinvoice.put("invoiceRef", "0");
			saveTempuserinvoice.put("invoiceRefStl", "");
			saveTempuserinvoice.put("invoicedelidate", "");
			saveTempuserinvoice.put("invManuRefNo", "");
			mydb.insert(STOCK_ORDER_INVOICESUMERY, null, saveTempuserinvoice);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		updateFcompanyBranch();
		mydb.close();
	}
	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='SECORD' AND BranchCode='" + currentUserTemp
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", LatestInvNumber);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}

	}
	protected void latestInvoiceRecord() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] resultserial = { "tempRepInvSerial" };
		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				if (selectLastinvrec.moveToLast()) {
					currentSerial = selectLastinvrec.getString(4);
					LatestInvState = selectLastinvrec.getString(5); // If
																	// invoice
																	// complete
					if (LatestInvState.equals(2)) {
						// saveTempuserDeails();
					} else {
					}
					selectLastinvrec.close();
				}
			} else {
				LatestInvNumber = "1";
				LatestInvState = "0";
				ActiveInvoice = "1";
				addNewInvoice();
			}
		} else {
			LatestInvNumber = "1";
			LatestInvState = "0";
			ActiveInvoice = "1";
			addNewInvoice();
		}
		mydb.close();
	}

	protected void agentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
				}

			}
		}
		mydb.close();
	}

	protected void invoiceTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SECORD")) {
						TransTypePrefix = cCharValue.trim();
					}

				}
			}
		}
		mydb.close();
	}

	// Print Account Description
	public void AddCustomerDetails(View view) {
		customerReloadTag = 202;
		etdminvno.setText("");
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		invcuscode = SetTransactionDesc.trim();
		viewDebtorDetails();
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);
	}

	private void viewDebtorDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowCusDet = null;
		try {
			allrowCusDet = mydb.query(ITEM_DEBTOR, null, "DebCode='"
					+ invcuscode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowCusDet != null) {
			if (allrowCusDet.getCount() > 0) {
				while (allrowCusDet.moveToNext()) {
					etdminvcusdis.setEnabled(true);
					invcusname = allrowCusDet.getString(2);
					invcusdiscount = allrowCusDet.getString(10);
					etdminvcustomer.setText(invcusname);
					etdminvcusdis.setText(invcusdiscount);
				}
			}
		}
	}

	public void AddLocationItemsDetails(View view) {
		Button des = (Button) view;
		refNoSummaryInvoice = des.getText().toString();
		viewInvoiceSummary();
		ListInvTag = 99;
		ListViewselectinvoices.setVisibility(view.GONE);
		ListViewInvHeaderButton.setVisibility(view.VISIBLE);
		ListViewInvHeaderDetails.setVisibility(view.VISIBLE);

	}

	private void viewInvoiceSummary() {
		// TODO Auto-generated method stub
		btnSelectStOrder.setEnabled(false);
		etdminvremarks.setEnabled(false);
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowinvsum = null;
		try {
			allrowinvsum = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"invoiceRef='" + refNoSummaryInvoice + "'", null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowinvsum != null) {
			if (allrowinvsum.getCount() > 0) {
				while (allrowinvsum.moveToNext()) {
					currentSerial = allrowinvsum.getString(4);

					String activeInvoiceValue = allrowinvsum.getString(7);
					String activeInvItemDiscount = allrowinvsum.getString(8);
					String activeInvCusDiscount = allrowinvsum.getString(9);
					String activeInvCusDiscountValue = allrowinvsum
							.getString(10);
					String InvoiceCustomerName = allrowinvsum.getString(12);
					String recordDate = allrowinvsum.getString(14);
					String activeInvoiceReturnValue = allrowinvsum
							.getString(17);
					String activeInvoiceRemarks = allrowinvsum.getString(18);
					String etsalesorderdeldate = allrowinvsum.getString(22);
					String activeInvoiceManuRefNo = allrowinvsum.getString(23);

					etdminvno.setText(refNoSummaryInvoice);
					etdminvdate.setText(recordDate);
					etdminvcustomer.setText(InvoiceCustomerName);
					etdminvremarks.setText(activeInvoiceRemarks);
					etdminvcusdis.setText(activeInvCusDiscount);

					double activeInvItemDiscountVal = Double
							.parseDouble(activeInvItemDiscount.replaceAll(
									"[,]", ""));
					activeInvItemDiscount = formatValues
							.format(activeInvItemDiscountVal);
					etdminvdiscount.setText(activeInvItemDiscount);

					double activeInvoiceReturnValueVal = Double
							.parseDouble(activeInvoiceReturnValue.replaceAll(
									"[,]", ""));
					activeInvoiceReturnValue = formatValues
							.format(activeInvoiceReturnValueVal);
					marketretval.setText(activeInvoiceReturnValue);

					double activeInvCusDiscountValueVal = Double
							.parseDouble(activeInvCusDiscountValue.replaceAll(
									"[,]", ""));
					activeInvCusDiscountValue = formatValues
							.format(activeInvCusDiscountValueVal);
					invoicedisval.setText(activeInvCusDiscountValue);

					double activeInvoiceValueVal = Double
							.parseDouble(activeInvoiceValue.replaceAll("[,]",
									""));
					activeInvoiceValue = formatValues
							.format(activeInvoiceValueVal);
					invoicetotval.setText(activeInvoiceValue);

					btnSelectStOrder.setText(etsalesorderdeldate);
					etdmsalesordermanuno.setText(activeInvoiceManuRefNo);
					INVSelectCustomer.setEnabled(false);
					INVSelectItems.setEnabled(false);
					// jana
				}
			}
		}
	}

	public DM_InvoiceSalesOrder() {
		// Assign current Date and Time Values to Variables
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_sales_order);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		dbHelperCustomer = new DM_CustomerList_Adapter(this);
		dbHelperCustomer.open();

		etdminvno = (Button) findViewById(R.id.etdminvno);
		btnSelectStOrder = (Button) findViewById(R.id.etsalesorderdeldate);
		etdminvdate = (EditText) findViewById(R.id.etdminvdate);
		etdminvcustomer = (EditText) findViewById(R.id.etdminvcustomer);
		etdminvremarks = (EditText) findViewById(R.id.etdminvremarks);
		etdminvdiscount = (EditText) findViewById(R.id.etdminvdiscount);
		etdmsalesordermanuno = (EditText) findViewById(R.id.etdmsalesordermanuno);
		etdminvcusdis = (EditText) findViewById(R.id.etdminvcusdis);
		etdminvcusdis.addTextChangedListener(calculateCustomerInvDiscount);
		etdminvcusdis
				.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(2) });
		etdminvCusdiscount = (EditText) findViewById(R.id.etdminvCusdiscount);
		etdminvCusdiscount.addTextChangedListener(calculateCusInvDisManuVal);
		etdminvCusdiscount
				.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(2) });
		// etsalesorderdeldate= (EditText)
		// findViewById(R.id.etsalesorderdeldate);
		marketretval = (EditText) findViewById(R.id.marketretval);
		invoicedisval = (EditText) findViewById(R.id.invoicedisval);
		invoicetotval = (EditText) findViewById(R.id.invoicetotval);
		myFilterCustomer = (EditText) findViewById(R.id.dminvfiltercustomer);

		customerSearchBox = (RelativeLayout) findViewById(R.id.customerSearchBox);
		INVSelectCustomer = (Button) findViewById(R.id.btninvselectcustomer);
		INVSelectItems = (Button) findViewById(R.id.btninvdetails);
		INVSave = (Button) findViewById(R.id.account_saveButton);
		INVPrint = (Button) findViewById(R.id.account_printButton);
		INVCancel = (Button) findViewById(R.id.account_cancelButton);
		INVUndo = (Button) findViewById(R.id.account_undoButton);
		CusListAllViewBtn = (Button) findViewById(R.id.cuslistallviewBtn);
		ListViewShowCustomers = (LinearLayout) findViewById(R.id.dminvoiceselectcus);
		ListViewInvHeaderButton = (LinearLayout) findViewById(R.id.invheaderbuttons);
		ListViewInvHeaderDetails = (LinearLayout) findViewById(R.id.dminvoiceheadersection);
		ListViewselectinvoices = (LinearLayout) findViewById(R.id.dminvoiceselectinvoices);
		etdminvdate.setText(getCurrentTimeString());
		
		currentuserTemp();
		populateCustomerList();
		updateCurrentSoSumary();
		invoiceTransType();
		agentPrefix();
		checkLatestInvoiceSerial();
		checkInvoiceSummary();
		viewInvoiceHeaderDetails();
		deviceName();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		long now = System.currentTimeMillis();
		Date today = new Date(now);
		Date tomorrow = new Date(now + 86400000); // 24 * 60 * 60 * 1000
		btnSelectStOrder.setText(dateFormat.format(tomorrow));
		/*
		 * System.out.println("Today: " + dateFormat.format(today) +
		 * "\nTomorrow: " + dateFormat.format(tomorrow));
		 */
		/*
		 * Log.v(TAG, "Tomorrow :"+ dateFormat.format(tomorrow)); String
		 * Currentdate = dateFormat.format(tomorrow);
		 */
		btnSelectStOrder.setText(dateFormat.format(tomorrow));

		CusListAllViewBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				customerSearchBox.setVisibility(view.VISIBLE);
				customerReloadTag = 404;
				populateCustomerDetailsList();
				// populateCustomerList();
				// reloadAllCustommers();
			}

		});
		// Select Delivery Date
		// Set ClickListener on btnSelectDate
		btnSelectStOrder.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				showDialog(DATE_DIALOG_ID);
			}
		});

		// Button touchup Event handling
		etdminvno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Button ACTION_DOWN", Toast.LENGTH_SHORT).show();
					 */
				} else if (action == MotionEvent.ACTION_UP) {
					ListViewselectinvoices.setVisibility(view.VISIBLE);
					ListViewInvHeaderButton.setVisibility(view.GONE);
					ListViewInvHeaderDetails.setVisibility(view.GONE);
					ShowInvoiceList();
					// jana
				}
				return false;

			}

		});

		if (TagId.equals(match)) {
			INVSave.setEnabled(true);
			//INVPrint.setEnabled(true);
			INVCancel.setEnabled(true);
			INVUndo.setEnabled(true);
			viewInvoiceHeaderDetails();
		}
		INVSelectItems.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (btnSelectStOrder.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_InvoiceSalesOrder.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("DELIVERY DATE");
					// Setting Dialog Message
					alertDialog.setMessage("Select Invoice Delivery Date..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}

				if (etdminvcustomer.length() == 0 || etdminvdate.length() == 0) {
					try {
						showDialog(DIALOG_SELECT_CUSTOMER);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					return;
				} else {
					// updateInvoiceSummery();
					updateInvoiceSumTable();
					Intent myIntent = new Intent(view.getContext(),
							DM_InvoiceSalesOrderDetails.class);
					myIntent.putExtra("TAGID", "4");
					startActivityForResult(myIntent, 0);
				}

			}

		});

		INVSelectCustomer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				myFilterCustomer.setText("");
				myFilterCustomer.requestFocus();
				customerSearchBox.setVisibility(view.GONE);
				customerReloadTag = 202;
				populateCustomerList();
				ListViewShowCustomers.setVisibility(view.VISIBLE);
				ListViewInvHeaderButton.setVisibility(view.GONE);
				ListViewInvHeaderDetails.setVisibility(view.GONE);

			}

		});
		
		
		//Last theree visit 
		// Invoice heder popup menu list
				popup_invmenubut = (Button) findViewById(R.id.dmpopupmenulist);
				popup_invmenubut.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(final View v) {
						// TODO Auto-generated method stub
						PopupMenu popup = new PopupMenu(DM_InvoiceSalesOrder.this,
								popup_invmenubut);
						popup.getMenuInflater().inflate(R.menu.dm_popup_invmenu,
								popup.getMenu());

						popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
							@TargetApi(Build.VERSION_CODES.HONEYCOMB)
							public boolean onMenuItemClick(MenuItem item) {
								//String currentMenuTitle = 
								
								slectedMenuOption = item.getTitle().toString();
								String chkcustomer = etdminvcustomer.getText()
										.toString();
								Log.v(TAG, "chkcustomer:" + slectedMenuOption.trim());

								if (etdminvcustomer.length() == 0) {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceSalesOrder.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("SELECT CUSTOMER");
									// Setting Dialog Message
									alertDialog
											.setMessage("Select Valid Customer First");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog.setButton("OK",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													alertDialog.dismiss();
												}
											});
									// Showing Alert Message
									alertDialog.show();
									alertDialog.setCanceledOnTouchOutside(false);

								} else {
									if(slectedMenuOption.equals("Last Three Visit")){
										displayLastThreeVisit(v);
									}
									else{
										displayCustomerOutstand(v);
										
									}
									Log.v(TAG, "VISIT 3 CALL");
								}
								return true;
							}

							private void displayCustomerOutstand(View v) {
								// TODO Auto-generated method stub
								
								Intent myIntent = new Intent(v.getContext(),
										DM_RetOutstanding_Information.class);
								myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
										| Intent.FLAG_ACTIVITY_NEW_TASK);
								myIntent.putExtra("TAGID", "SO/"+invcuscode);
								startActivityForResult(myIntent, 0);
								finish();
							}

							private void displayLastThreeVisit(View v) {
								Log.v(TAG, "VISIT 3 CALL METHOD");
								// TODO Auto-generated method stub
								Intent myIntent = new Intent(v.getContext(),
										DM_Customer_Last_Three_SO_Visit.class);
								myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
										| Intent.FLAG_ACTIVITY_NEW_TASK);
								myIntent.putExtra("REPORTNAME", slectedMenuOption + "/"
										+ invcuscode);
								startActivityForResult(myIntent, 0);
								finish();
							}
						});

						popup.show();
					}
				});

	}
	
	
	private void checkInvoiceSummary() {
		// TODO Auto-generated method stub
		Log.v(TAG, "****checkInvoiceSummary SO****");
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor checkInvoiceSerial = null;

		try {
			checkInvoiceSerial = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"tempRepInvSerial='" + strLatestInvoiceSerial
							+ "' AND repusername='" + currentUserTemp + "'",
					null, null, null, null);
		} catch (Exception e) {
		}
		ActiveInvoice = "1";
		if (checkInvoiceSerial != null) {
			if (checkInvoiceSerial.getCount() <= 0) {
				try {
					ContentValues saveTempuserinvoice = new ContentValues();
					saveTempuserinvoice.put("repusername", currentUserTemp);
					saveTempuserinvoice.put("repprefix", currentUserPrefix);
					saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
					saveTempuserinvoice.put("tempRepInvSerial", strLatestInvoiceSerial);
					saveTempuserinvoice.put("invoiceComplete", "0");
					saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
					saveTempuserinvoice.put("activeInvoiceValue", "0");
					saveTempuserinvoice.put("activeInvItemDiscount", "0");
					saveTempuserinvoice.put("activeInvCusDiscount", "0");
					saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
					saveTempuserinvoice.put("InvoiceCustomerCode", "0");
					saveTempuserinvoice.put("InvoiceCustomerName", "");
					saveTempuserinvoice.put("InvoiceSynchState", "0");
					saveTempuserinvoice.put("recordDate", getCurrentTimeString());
					saveTempuserinvoice.put("recordSynchDate", "0");
					saveTempuserinvoice.put("invlateststate", "9");
					saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
					saveTempuserinvoice.put("activeInvoiceRemarks", "");
					saveTempuserinvoice.put("invoiceNoOfItems", "0");
					saveTempuserinvoice.put("invoiceRef", "0");
					saveTempuserinvoice.put("invoiceRefStl", "0");
					saveTempuserinvoice.put("invoicedelidate", "0");
					saveTempuserinvoice.put("invManuRefNo", "0");
					mydb.insert(STOCK_ORDER_INVOICESUMERY, null, saveTempuserinvoice);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
		checkInvoiceSerial.close();
		mydb.close();
	}

		// *******Get Latest Invoice Serial**********
		private void checkLatestInvoiceSerial() {
			// TODO Auto-generated method stub
			Log.v(TAG, "****checkLatestInvoiceSerial****");
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectInvoiceSerial = null;

			try {
				selectInvoiceSerial = mydb.query(INV_COMPANY_BRANCH, null,
						"cSettingsCode='SECORD' AND BranchCode='" + currentUserTemp
								+ "'", null, null, null, null);
			} catch (Exception e) {
			}

			if (selectInvoiceSerial != null) {
				if (selectInvoiceSerial.getCount() > 0) {
					while (selectInvoiceSerial.moveToNext()) {
						String cSettingsCode = selectInvoiceSerial.getString(3);
						String nNumVal = selectInvoiceSerial.getString(4);
						strLatestInvoiceSerial = nNumVal.trim();
					}
				} else {
					strLatestInvoiceSerial = "1";
					try {
						ContentValues newAdjustment = new ContentValues();
						newAdjustment.put("BranchCode", currentUserTemp);
						newAdjustment.put("RecordId", "1");
						newAdjustment.put("cSettingsCode", "SECORD");
						newAdjustment.put("nNumVal", strLatestInvoiceSerial);
						mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);

					} catch (Exception e) {
						Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
								.show();
					}
					mydb.close();
				}
			}
			selectInvoiceSerial.close();
			mydb.close();
			return;
		}
	
	
	
	
	
	
//------------------------------------------------------------30012014
	private void updateCurrentSoSumary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateTxnDate = null;
		try {
			updateTxnDate = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invlateststate='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		
		try {
			if (updateTxnDate != null) {
				if (updateTxnDate.getCount() > 0) {
					while (updateTxnDate.moveToNext()) {
						ContentValues valueupdateInvHeadUpdateSum = new ContentValues();
						valueupdateInvHeadUpdateSum.put("recordDate", getCurrentTimeString());
						mydb.update(STOCK_ORDER_INVOICESUMERY,
								valueupdateInvHeadUpdateSum, "repusername='" + currentUserTemp
								+ "' AND invlateststate='9'", null);
					}
				}
			}
		} catch (Exception e) {
		}
		updateTxnDate.close();
		mydb.close();
	}

	protected void updateInvoiceSumTable() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curCurrentSumRecord = null;
		try {
			String querySelectInvSum = "SELECT * From fstockordInvoiceSumery Where activeInvoice ='1'";
			curCurrentSumRecord = mydb.rawQuery(querySelectInvSum, null);
		} catch (Exception e) {

		}
		if (curCurrentSumRecord != null) {
			if (curCurrentSumRecord.getCount() > 0) {
				while (curCurrentSumRecord.moveToNext()) {
					ContentValues valueupdateInvSum = new ContentValues();
					String invUpdateSerial = curCurrentSumRecord.getString(4);
					valueupdateInvSum.put("InvoiceCustomerCode", invcuscode);
					valueupdateInvSum.put("InvoiceCustomerName", invcusname);
					String DisPercentageVal = etdminvcusdis.getText()
							.toString();
					if (DisPercentageVal.trim().length() != 0) {
						valueupdateInvSum.put("activeInvCusDiscount",
								DisPercentageVal);
					} else {
						valueupdateInvSum.put("activeInvCusDiscount", "0.00");
					}

					String DisVal = etdminvCusdiscount.getText().toString();
					if (DisVal.trim().length() != 0) {
						valueupdateInvSum.put("activeInvCusDiscountValue",
								DisVal);
					} else {
						valueupdateInvSum.put("activeInvCusDiscountValue",
								"0.00");
					}

					valueupdateInvSum.put("activeInvoiceRemarks",
							etdminvremarks.getText().toString());
					valueupdateInvSum.put("invoicedelidate", btnSelectStOrder
							.getText().toString()); // latest
					valueupdateInvSum.put("invManuRefNo", etdmsalesordermanuno
							.getText().toString());
					mydb.update(STOCK_ORDER_INVOICESUMERY, valueupdateInvSum,
							"tempRepInvSerial=" + invUpdateSerial, null);
				}
			}
		}
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	// Register DatePickerDialog listener
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// the callback received when the user "sets" the Date in the
		// DatePickerDialog
		int count;

		public void onDateSet(DatePicker view, int yearSelected,
				int monthOfYear, int dayOfMonth) {
			count = count + 1;

			mYear = yearSelected;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			String mMonthStr = Integer.toString(mMonth);
			String mDayStr = Integer.toString(mDay);
			String currentDate = getCurrentTimeStringDel().toString();
			String deliverDate = mMonthStr + "/" + mDayStr + "/" + mYear;
			printDeliverDate = mDayStr + "/" + mMonthStr + "/" + mYear;
			Log.v(TAG, "currentDate 1:" + currentDate);
			Log.v(TAG, "deliverDate 2:" + deliverDate);
			try {
				Date date1 = (Date) sdf.parse(currentDate.replaceAll(
						"\\p{Cntrl}", "").trim());
				Date date2 = (Date) sdf.parse(deliverDate.replaceAll(
						"\\p{Cntrl}", "").trim());
				Log.v(TAG, "date1 F1:" + date1);
				Log.v(TAG, "date2 F2:" + date2);

				if (date1.compareTo(date2) > 0) {
					Log.v("app", "Date1 is after Date2   1:" + count);
					if (count == 1) {
						Log.v("app", "Date1 is after Date2  2:" + count);
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceSalesOrder.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID DILIVERY DATE");
						// Setting Dialog Message
						alertDialog
								.setMessage("Past Date,s Not Allowed.Select Current/Future Delivery Date.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										count = 0;
										// btnSelectStOrder.setText("");
										showDialog(DATE_DIALOG_ID);
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}
				} else if (date1.compareTo(date2) < 0) {
					// Set the Selected Date in Select date Button
					btnSelectStOrder.setText(printDeliverDate);
					Log.v("app", "Date1 is before Date2");
					count = 0;
				} else if (date1.compareTo(date2) == 0) {
					// Set the Selected Date in Select date Button
					btnSelectStOrder.setText(printDeliverDate);
					Log.v("app", "Date1 is equal to Date2");
					count = 0;
				}
				count = 0;
				btnSelectStOrder.setText(printDeliverDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	protected void ShowInvoiceList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewInvoices);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colinvoice_1", "colinvoice_2" };
		int[] totrdes = new int[] { R.id.invListingViewNo,
				R.id.invListingViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			/*
			 * allrowtypedes = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
			 * "repusername='" + currentUserTemp + "' AND invoiceComplete ='2'",
			 * null, null, null, null);
			 */
			String query = "SELECT OH.RefNo,OH.AddUser,OH.DebCode,DE.DebCode,DE.DebName,DE.TownCode,TW.TownCode,TW.TownName,OS.remprepinv_id,OS.invoiceComplete,OS.repusername,OS.invoiceComplete,OS.tempRepInvNoCode,OS.tempRepInvSerial FROM FOrdHed OH INNER JOIN fDebtor DE ON DE.DebCode = OH.DebCode INNER JOIN fTown TW ON TW.TownCode = DE.TownCode INNER JOIN fstockordInvoiceSumery  OS ON OS.invoiceRef = OH.RefNo Where OS.repusername ='"
					+ currentUserTemp + "' AND OS.invoiceComplete ='2' ORDER BY invoiceRef DESC";

			allrowtypedes = mydb.rawQuery(query, null);

		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					/*
					 * String remprepinv_id = allrowtypedes.getString(0); String
					 * tempRepInvNoCode = allrowtypedes.getString(3); String
					 * tempRepInvSerial = allrowtypedes.getString(4); String
					 * invRefNo = allrowtypedes.getString(0);
					 */
					INVPrint.setEnabled(true);
					String invRefNo = allrowtypedes.getString(0);
					String remprepinv_id = allrowtypedes.getString(3);
					String DebName = allrowtypedes.getString(4);
					String TownName = allrowtypedes.getString(7);
					String remprepinv_ids = allrowtypedes.getString(8);
					String tempRepInvNoCode = allrowtypedes.getString(12);
					String tempRepInvSerial = allrowtypedes.getString(13);

					String columncusdet = remprepinv_ids + "/"
							+ tempRepInvNoCode + "/" + tempRepInvSerial;
					String flagno = "00000";
					/*
					 * String PrintRefNo = tempRepInvNoCode + "/" + flagno +
					 * tempRepInvSerial;
					 */
					String PrintRefNo = invRefNo + " - " +DebName;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colinvoice_1", PrintRefNo);
					maptrdes.put("colinvoice_2", invRefNo);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_pre_invoice_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					UserAreaCode = selectCurrentuserrec.getString(9);
					UserDealCode = selectCurrentuserrec.getString(10);
					UserRouteCode = selectCurrentuserrec.getString(11);
				}
			}
		}
		latestInvoiceNumber();// Get current invoice temp
		// number(currentInvoiceTempNo)
	}

	private void viewInvoiceHeaderDetails() {
		Log.v(TAG, "*******viewInvoiceHeaderDetails*******");
		etdminvCusdiscount.setEnabled(true);
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerow = null;
		try {
			latestinvoicerow = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"invlateststate ='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (latestinvoicerow != null) {
			if (latestinvoicerow.getCount() > 0) {
				while (latestinvoicerow.moveToNext()) {
					String repusername = latestinvoicerow.getString(1);
					String tempRepInvNoCode = latestinvoicerow.getString(3);
					invoiceSerial = latestinvoicerow.getString(4);
					String tempRepInvSerial = latestinvoicerow.getString(4);
					String invoiceComplete = latestinvoicerow.getString(5);
					String activeInvoiceValue = latestinvoicerow.getString(7);// Take
																				// tot
																				// val
					String activeInvItemDiscount = latestinvoicerow
							.getString(8);
					String activeInvCusDiscount = latestinvoicerow.getString(9);// cus
																				// discount
																				// rate
					String activeInvCusDiscountValue = latestinvoicerow
							.getString(10);
					invcuscode = latestinvoicerow.getString(11);
					invcusname = latestinvoicerow.getString(12);
					String recordDate = latestinvoicerow.getString(14);
					String activeInvoiceReturnValue = latestinvoicerow
							.getString(17);
					String activeInvoiceremark = latestinvoicerow.getString(18);
					String invoiceRef = latestinvoicerow.getString(20);
					String invoiceStOrdRef = latestinvoicerow.getString(21);
					invoiceDeliDate = latestinvoicerow.getString(22);

					// etdmstorderno.setText(invoiceStOrdRef);
					// Print Date
					etdminvdate.setText(recordDate);
					// Print Deliver Date
					btnSelectStOrder.setText(invoiceDeliDate);
					// Customer name
					etdminvcustomer.setText(invcusname);
					// Invoice remarks
					etdminvremarks.setText(activeInvoiceremark);
					// Market return total value
					marketretval.setText(activeInvoiceReturnValue);
					// Discount Value
					invoicedisval.setText(activeInvItemDiscount);
					StrMainLineDisValTot = Double
							.parseDouble(activeInvItemDiscount.replaceAll(
									"[,]", ""));
					// Invoice Total
					invoicetotval.setText(activeInvoiceValue);
					StrMainInvValTot = Double.parseDouble(activeInvoiceValue
							.replaceAll("[,]", ""));

					// Customer Discount Ratio
					etdminvcusdis.setText(activeInvCusDiscount);
					// Customer Discount Value
					etdminvCusdiscount.setText(activeInvCusDiscountValue);

					// Total Invoice Percentage Discount Value
					InvValueItems = Double.parseDouble(activeInvoiceValue
							.replaceAll("[,]", "").trim());// Invoice Tot Val
					// CustomerDiscout Rate
					InvDiscountValueCustomer = Double
							.parseDouble(activeInvCusDiscount.replaceAll("[,]",
									""));
					TotCustomerInvDiscount = (InvValueItems * InvDiscountValueCustomer) / 100;
					TotCustomerInvDiscount = Math
							.round(TotCustomerInvDiscount * 100) / 100.0d;
					PrintTotCustomerInvDiscount = Double
							.toString(TotCustomerInvDiscount);
					// ********************************************************************

					try {
						if (tempRepInvSerial.length() == 1) {
							String newInvNumberStr = "00000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 2) {
							String newInvNumberStr = "0000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 3) {
							String newInvNumberStr = "000" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 4) {
							String newInvNumberStr = "00" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else if (tempRepInvSerial.length() == 5) {
							String newInvNumberStr = "0" + tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						} else {
							String newInvNumberStr = tempRepInvSerial;
							currentInvoiceTempRefCode = tempRepInvNoCode.trim()
									+ "/" + newInvNumberStr;
						}
						etdminvno.setText(currentInvoiceTempRefCode);
						etdminvdiscount.setText(PrintTotCustomerInvDiscount);
					} catch (Exception e) {
						Toast.makeText(getApplicationContext(),
								"Error Occured..", Toast.LENGTH_SHORT).show();
					}
					SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
					long now = System.currentTimeMillis();
					Date today = new Date(now);
					Date tomorrow = new Date(now + 86400000); // 24 * 60 * 60 * 1000
					btnSelectStOrder.setText(dateFormat.format(tomorrow));
				}
			}
		}
		latestinvoicerow.close();
		mydb.close();
	}

	private void latestInvoiceNumber() {
		// TODO Auto-generated method stub
		Log.v(TAG, "*******latestInvoiceNumber*******");
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor latestinvoicerowdet = null;
		String columsLInv[] = { "activeInvoice" };

		try {
			latestinvoicerowdet = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"repusername='" + currentUserTemp
							+ "' AND invoiceComplete='1'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (latestinvoicerowdet != null) {
			if (latestinvoicerowdet.getCount() > 0) {
				while (latestinvoicerowdet.moveToNext()) {
					String repusername = latestinvoicerowdet.getString(1);
					invoiceSerial = latestinvoicerowdet.getString(4);
					String invoiceComplete = latestinvoicerowdet.getString(5);
					String activeInvoiceValue = latestinvoicerowdet
							.getString(7);// Take tot val
					String activeInvItemDiscount = latestinvoicerowdet
							.getString(8);
					String activeInvCusDiscount = latestinvoicerowdet
							.getString(9);// cus discount rate
					String activeInvCusDiscountValue = latestinvoicerowdet
							.getString(10);
					invcuscode = latestinvoicerowdet.getString(11);
					invcusname = latestinvoicerowdet.getString(12);
					String recordDate = latestinvoicerowdet.getString(14);
					String activeInvoiceReturnValue = latestinvoicerowdet
							.getString(17);
					String activeInvoiceremark = latestinvoicerowdet
							.getString(18);
					String invoiceRef = latestinvoicerowdet.getString(20);
					String invoiceStOrdRef = latestinvoicerowdet.getString(21);

					invoicetotval.setText(activeInvoiceValue);
					if (invoiceComplete.equals("0")) {
						// etdmstorderno.setText(invoiceStOrdRef);
						etdminvcustomer.setText(invcusname);
						etdminvcusdis.setText(activeInvCusDiscount);
					} else {
						if (TagId.equals("3")) {
							if (invoiceRef.equals("0")) {
								// Print Date
								etdminvdate.setText(recordDate);
								// Customer name
								etdminvcustomer.setText(invcusname);
								// Invoice remarks
								etdminvremarks.setText(activeInvoiceremark);
								// Invoice market return value
								marketretval.setText(activeInvoiceReturnValue);
								// Discount Value
								invoicedisval.setText(activeInvItemDiscount);
								StrMainLineDisValTot = Double
										.parseDouble(activeInvItemDiscount
												.replaceAll("[,]", ""));
								// Invoice Total
								invoicetotval.setText(activeInvoiceValue);
								StrMainInvValTot = Double
										.parseDouble(activeInvoiceValue
												.replaceAll("[,]", ""));

								// Customer Discount Ratio
								etdminvcusdis.setText(activeInvCusDiscount);
								// Customer Discount Value
								etdminvCusdiscount
										.setText(activeInvCusDiscountValue);
							}
						} else if (TagId.equals(match)) {
							INVSave.setEnabled(true);
							INVCancel.setEnabled(true);
							INVUndo.setEnabled(true);
							viewInvoiceHeaderDetails();
						}
					}
				}
			}
		} else {
			Toast.makeText(getApplicationContext(), "Enter New Invoice***",
					Toast.LENGTH_SHORT).show();
		}
		latestinvoicerowdet.close();
		mydb.close();
	}

	private void populateCustomerList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewcutommer);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			if (customerReloadTag == 202) {
				String querySelectDebtor = "SELECT RD.DebCode,RD.RouteCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
						+ UserRouteCode + "'";
				allrowtypedes = mydb.rawQuery(querySelectDebtor, null);
			} else if (customerReloadTag == 404) {
				populateCustomerDetailsList();
				/*
				 * String querySelectDebtor =
				 * "SELECT RD.DebCode,RD.RouteCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode"
				 * ; curListCustomer = mydb.rawQuery(querySelectDebtor, null);
				 */
			}

		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String customercode = allrowtypedes.getString(0);
					String customername = allrowtypedes.getString(2);
					String customerdiscount = allrowtypedes.getString(3);
					String columncusdet = customercode + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", customercode);
					maptrdes.put("coldes_2", customercode + " : "
							+ customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	@SuppressLint("NewApi")
	private void populateCustomerDetailsList() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelperCustomer.fetchAllCustommers();

		// The desired columns to be bound
		String[] columns = new String[] { DM_CustomerList_Adapter.KEY_CUSCODE,
				DM_CustomerList_Adapter.KEY_CUSNAME };
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoicecustommer, R.id.invcustomername, };

		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapterCusomer = new SimpleCursorAdapter(this,
				R.layout.dm_customer_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listviewcutommer);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterCusomer);

		myFilterCustomer.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterCusomer.getFilter().filter(s.toString());
			}
		});

		dataAdapterCusomer.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelperCustomer.fetchAllCustommersByName(constraint
						.toString());
			}
		});
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	private String getCurrentTimeStringDel() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormatdel = new SimpleDateFormat("MM/dd/yyyy");
		String date_to_stringdel = ddMMMyyFormatdel.format(dateNow);
		return date_to_stringdel;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CANCEL_INVOICE:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Cancel Current Sales Order Details...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_INVOICE:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Sales Order Details...");
			dialogbuilderu.setView(dialogviewu);
			InvoiceHeaderAlert = dialogbuilderu.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_PRINT_INVOICE:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			InvoiceHeaderAlert = dialogbuilderp.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SAVE_INVOICE:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_save_invoice, null);

			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Sales Order Saved Successfully...");
			dialogbuilders.setView(dialogviews);
			InvoiceHeaderAlert = dialogbuilders.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SELECT_CUSTOMER:
			LayoutInflater inflatercus = LayoutInflater.from(this);
			View dialogviewcus = inflatercus.inflate(
					R.layout.dm_dialog_select_customer, null);

			AlertDialog.Builder dialogbuildercus = new AlertDialog.Builder(this);
			dialogbuildercus.setTitle("Please Select Customer...");
			dialogbuildercus.setView(dialogviewcus);
			InvoiceHeaderAlert = dialogbuildercus.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DATE_DIALOG_ID:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}

		return InvoiceHeaderAlert;
	}

	// ***********************************************************************************
	// Calculate Values With Discount Ratio
	private TextWatcher calculateCustomerInvDiscount = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			if (etdminvcusdis.length() != 0 && etdminvCusdiscount.length() == 0) {
				StrManualInvAmount = 0.00;
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} else {
					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double newDiscountedTotVal = StrMainInvValTot
							- discountedTotValRatioVal;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() != 0
					&& etdminvCusdiscount.length() != 0) {
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} /*
				 * else if (StrManualDiscount > StrMainInvValTot) {
				 * //callDiscountValueAmtExceed(); StrManualDiscount = 0.00;
				 * etdminvCusdiscount.setText("0.00"); }
				 */else {
					String StrInvDiscountHedVal = etdminvCusdiscount.getText()
							.toString();
					double StrInvDiscountHedAmount = Double
							.parseDouble(StrInvDiscountHedVal.replaceAll("[,]",
									""));

					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double headerTotDiscount = discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					double newDiscountedTotVal = StrMainInvValTot
							- headerTotDiscount;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() == 0
					&& etdminvCusdiscount.length() != 0) {
				String StrInvDiscountHedVal = etdminvCusdiscount.getText()
						.toString();
				double StrInvDiscountHedAmount = Double
						.parseDouble(StrInvDiscountHedVal.replaceAll("[,]", ""));

				// Do Calculations
				etdminvdiscount.setText("0.00");

				// Calculate Current Total Dicount Value
				double newDiscountTot = StrMainLineDisValTot
						+ StrInvDiscountHedAmount;
				String PrintnewDiscountTot = formatValues
						.format(newDiscountTot);
				invoicedisval.setText(PrintnewDiscountTot);

				// Calculate Current Invoice Value
				double newDiscountedTotVal = StrMainInvValTot
						- StrInvDiscountHedAmount;
				String PrintnewDiscountedTotVal = formatValues
						.format(newDiscountedTotVal);
				invoicetotval.setText(PrintnewDiscountedTotVal);
			} else {
				etdminvdiscount.setText("0.00");
				// print discountcc
				String newStrMainInvDisValTot = formatValues
						.format(StrMainLineDisValTot);
				invoicedisval.setText(newStrMainInvDisValTot);
				// print total
				String newStrMainInvValTot = formatValues
						.format(StrMainInvValTot);
				invoicetotval.setText(newStrMainInvValTot);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}

	};

	// ***********************************************************************************
	private TextWatcher calculateCusInvDisManuVal = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			if (etdminvcusdis.length() != 0 && etdminvCusdiscount.length() == 0) {
				StrManualInvAmount = 0.00;
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} else {
					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double newDiscountedTotVal = StrMainInvValTot
							- discountedTotValRatioVal;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() != 0
					&& etdminvCusdiscount.length() != 0) {
				// Calculate Discount Percentage Ratio
				String StrInvDisRatio = etdminvcusdis.getText().toString();
				StrInvDisRatioAmount = Double.parseDouble(StrInvDisRatio
						.replaceAll("[,]", ""));
				ratio = StrInvDisRatioAmount / 100.00;

				if (ratio > 1) {
					callDiscountRatioExceedAlert();
				} /*
				 * else if (StrManualDiscount > StrMainInvValTot) {
				 * //callDiscountValueAmtExceed(); StrManualDiscount = 0.00;
				 * etdminvCusdiscount.setText("0.00"); }
				 */else {
					String StrInvDiscountHedVal = etdminvCusdiscount.getText()
							.toString();
					double StrInvDiscountHedAmount = Double
							.parseDouble(StrInvDiscountHedVal.replaceAll("[,]",
									""));

					// Do Calculations
					double discountedTotValRatioVal = StrMainInvValTot * ratio;
					String PrintdiscountedTotValRatioVal = formatValues
							.format(discountedTotValRatioVal);
					etdminvdiscount.setText(PrintdiscountedTotValRatioVal);

					// Calculate Current Total Dicount Value
					double newDiscountTot = StrMainLineDisValTot
							+ discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					String PrintnewDiscountTot = formatValues
							.format(newDiscountTot);
					invoicedisval.setText(PrintnewDiscountTot);

					// Calculate Current Invoice Value
					double headerTotDiscount = discountedTotValRatioVal
							+ StrInvDiscountHedAmount;
					double newDiscountedTotVal = StrMainInvValTot
							- headerTotDiscount;
					String PrintnewDiscountedTotVal = formatValues
							.format(newDiscountedTotVal);
					invoicetotval.setText(PrintnewDiscountedTotVal);
				}
			} else if (etdminvcusdis.length() == 0
					&& etdminvCusdiscount.length() != 0) {
				String StrInvDiscountHedVal = etdminvCusdiscount.getText()
						.toString();
				double StrInvDiscountHedAmount = Double
						.parseDouble(StrInvDiscountHedVal.replaceAll("[,]", ""));

				// Do Calculations
				etdminvdiscount.setText("0.00");

				// Calculate Current Total Dicount Value
				double newDiscountTot = StrMainLineDisValTot
						+ StrInvDiscountHedAmount;
				String PrintnewDiscountTot = formatValues
						.format(newDiscountTot);
				invoicedisval.setText(PrintnewDiscountTot);

				// Calculate Current Invoice Value
				double newDiscountedTotVal = StrMainInvValTot
						- StrInvDiscountHedAmount;
				String PrintnewDiscountedTotVal = formatValues
						.format(newDiscountedTotVal);
				invoicetotval.setText(PrintnewDiscountedTotVal);
			} else {
				etdminvdiscount.setText("0.00");
				// print discountcc
				String newStrMainInvDisValTot = formatValues
						.format(StrMainLineDisValTot);
				invoicedisval.setText(newStrMainInvDisValTot);
				// print total
				String newStrMainInvValTot = formatValues
						.format(StrMainInvValTot);
				invoicetotval.setText(newStrMainInvValTot);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

		}

	};

	protected void callDiscountRatioExceedAlert() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_InvoiceSalesOrder.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("ITEMS DISCOUNTING");
		// Setting Dialog Message
		alertDialog
				.setMessage("Invalid Appcation Invoice Discount Items Percentage.Maximum Percentage Allowed 100%");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int which) {
				ratio = 0.00;
				ratioManu = 0.00;
				etdminvcusdis.setText("");
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;

	}

	protected void callDiscountValueAmtExceed() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_InvoiceSalesOrder.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("INVALID INVOICE DISCOUNTING");
		// Setting Dialog Message
		alertDialog
				.setMessage("Total Invoice Discount Exceed.Discount Amount Can't Exceed Total Invoice Value..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int which) {
				StrManualDiscount = 0.00;
				etdminvCusdiscount.setText("");
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	// ==================================
	public class DecimalDigitsInputFilter implements InputFilter {

		private final int decimalDigits;

		/**
		 * Constructor.
		 * 
		 * @param decimalDigits
		 *            maximum decimal digits
		 */
		public DecimalDigitsInputFilter(int decimalDigits) {
			this.decimalDigits = decimalDigits;
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {

			int dotPos = -1;
			int len = dest.length();
			for (int i = 0; i < len; i++) {
				char c = dest.charAt(i);
				if (c == '.' || c == ',') {
					dotPos = i;
					break;
				}
			}
			if (dotPos >= 0) {

				// protects against many dots
				if (source.equals(".") || source.equals(",")) {
					return "";
				}
				// if the text is entered before the dot
				if (dend <= dotPos) {
					return null;
				}
				if (len - dotPos > decimalDigits) {
					return "";
				}
			}

			return null;
		}

	}
}
